//
//  HXDPlusPictureView.swift
//  weibo
//
//  Created by huxuedong on 15/12/14.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

private let HXDPlusPictureViewCellID = "HXDPlusPictureViewCell"

class HXDPlusPictureView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate {

    //定义添加图片的闭包
    var addImageClosure: (() -> ())?
    //懒加载图片数组
    lazy var images: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        //注册cell
        registerClass(HXDPlusPictureViewCell.self, forCellWithReuseIdentifier: HXDPlusPictureViewCellID)
        dataSource = self
        delegate = self
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //隐藏当前HXDPlusPictureView视图
        hidden = true
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //设置流水布局
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        let margin: CGFloat = 5
        //每个cell的宽高
        let itemSizeW = CGFloat(Int(width - margin * 2) / 3)
        //布局范围
        layout.itemSize = CGSize(width: itemSizeW, height: itemSizeW)
        //列间距
        layout.minimumInteritemSpacing = margin
        //行间距
        layout.minimumLineSpacing = margin
    }
    
    //往当前视图添加图片
    func addImage(image: UIImage) {
        images.append(image)
        reloadData()
        hidden = false
    }

}

//数据源和代理方法
extension HXDPlusPictureView {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count = images.count
        //为防止数组越界(添加图片按钮)，除没有图片或者填满9张图片外，其余cell的个数钧增加1
        return (count == 0 || count == 9) ? count : count + 1
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HXDPlusPictureViewCellID, forIndexPath: indexPath) as! HXDPlusPictureViewCell
        //当前cell与图片个数相等时(第0个或第9个)
        if indexPath.item == images.count {
            //不设置添加图片按钮的图片
            cell.image = nil
        } else {
            //从数组中设置图片
            cell.image = images[indexPath.item]
        }
        //记录当前indexPath
        cell.indexPath = indexPath
        //执行删除按钮的闭包
        cell.deleteButtonClosure = {[weak self](Indexable: NSIndexPath) -> () in
            //将当前点击的图片从数组中移除
            self?.images.removeAtIndex(indexPath.item)
            self?.reloadData()
            self?.hidden = self?.images.count == 0
        }
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //取消点击的cell的选中状态
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        //如果点击的是添加按钮
        if indexPath.item == images.count {
            //调用添加图片的闭包
            addImageClosure?()
        }
    }
    
}

class HXDPlusPictureViewCell: UICollectionViewCell {
    
    private lazy var imageView: UIImageView = UIImageView()
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        return button
    }()
    
    //定义删除按钮的闭包
    var deleteButtonClosure: ((indexPath: NSIndexPath) -> ())?
    var indexPath: NSIndexPath?
    
    var image: UIImage? {
        didSet {
            //如果cell中没有添加图片
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            } else {
                imageView.image = image
                imageView.highlightedImage = nil
            }
            deleteButton.hidden = image == nil
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(contentView)
            make.top.equalTo(contentView)
        }
    }
    
    @objc private func deleteButtonClick() {
        //调用删除按钮的闭包
        deleteButtonClosure?(indexPath: indexPath!)
    }
    
}
